<template>
  <div class="home">
    <div class="qrcode" ref="qrCodeUrl"></div>
    <div>
      <div>二维码有效期倒计时:{{times}}</div>
      <br/>
      <button>点击刷新二维码</button>
    </div>
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
import axios from 'axios'
import QRCode from 'qrcodejs2'

export default {
  name: 'Home',
  data () {
    return {
      times: 0,
      token: ''
    }
  },
  components: {
    HelloWorld
  },
  methods: {
    // 获取二维码
    getQrcode () {
      axios.get('http://127.0.0.1:8000/scan/getQrcodeContent').then(res => {
        this.creatQrCode(res.data.content)
        this.times = res.data.expireTime
        this.token = res.data.token
        // 开启倒计时
        this.timer = setInterval(() => {
          this.times--
          if (this.times === 0) {
            // 结束计时
            clearInterval(this.timer)
            // 重新获取二维码
            this.getQrcode()
          }
        }, 1000)
        // 开启扫码结果查询
        this.getQrcodeStatus()
      })
    },

    getQrcodeStatus () {
      // 查询二维码结果
      this.qtimer = setInterval(() => {
        axios.get('http://127.0.0.1:8000/scan/getQrcodeStatus', { params: { token: this.token } }).then(res => {
          console.log('结果', JSON.stringify(res.data))
        })

        if (this.times === 0) {
          clearInterval(this.qtimer)
        }
      }, 1500)
    },

    // 生成二维码
    creatQrCode (content) {
      this.$refs.qrCodeUrl = ''
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: content, // 需要转换为二维码的内容
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      console.log(qrcode)
    }
  },
  mounted () {
    this.getQrcode()
  }
}
</script>
<style>
  .qrcode{
    margin-top: 10px;
    margin-bottom: 10px;

  }
  .home{
    display: flex;
    flex-direction: column;
    align-items: center;
  }
</style>
